package com.qfjy.project.weixin.api.accessToken;

import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Component
public class AccessTokenRedis {
    @Autowired
    private RedisTemplate<String ,Object> redisTemplate;
    @Resource(name="redisTemplate")
     private ValueOperations<String,String> string;
    private static  String ACCESS_TOKEN_KEY="access_token_key";
    public String getAccessTokenVal(){
        if(redisTemplate.hasKey(ACCESS_TOKEN_KEY)){
          return  string.get(ACCESS_TOKEN_KEY);
        }else {
           String accessToken=this.sendWeiXinApi();
           string.set("ACCESS_TOKEN_KEY",accessToken);
           redisTemplate.expire(ACCESS_TOKEN_KEY,5, TimeUnit.SECONDS);
           return accessToken;
        }

    }

    private static String WEIXIN_API_GET_ACEESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";


    private String sendWeiXinApi(){
        String url=WEIXIN_API_GET_ACEESS_TOKEN_URL.replace("APPID", MenuManager.appId).replace("APPSECRET",MenuManager.appSecret);
        JSONObject jsonObject = WeixinUtil.httpRequest(url, "GET", null);
        return jsonObject.getString("access_token");
    }

}